#include <GL/glew.h>
#include <GL/freeglut.h>
#include <cstdio>
#include <common/common.hpp>

GLfloat vertices[] = {
	// triangle 1
    -0.5f, -0.5f, 
     0.5f,  0.5f,
    -0.5f,  0.5f,

    // triangle 2
    -0.5f, -0.5f, 
     0.5f, -0.5f, 
     0.5f,  0.5f,

    // line 1
    -0.5f,  0.0f, 
     0.5f,  0.0f,

    // mallets
     0.0f, -0.25f, 
     0.0f,  0.25f
};

static GLuint _program;
static GLuint _colorloc;

static GLboolean
init() {
	GLenum err = glewInit();
	if (err != GLEW_OK) {
		logv("fail to init glew");
		return GL_FALSE;
	}

	if (!GLEW_VERSION_3_3) {
		logv("not support for ogl3.3");
		return GL_FALSE;
	}
	logv("support for ogl3.3");

	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); // to enable set gl_PointSize in vertex shader

    _program = shader_util::linkprogram("./res/simple_vertex_shader.glsl", "./res/simple_fragment_shader.glsl");
    if (_program == 0)
    	return GL_FALSE;

    _colorloc = glGetUniformLocation(_program, "u_fragcolor");
    return GL_TRUE;
}

static void
cb_display() {
	logv("cb_display");
   	
   	glClear(GL_COLOR_BUFFER_BIT);

   	glUseProgram(_program);
   		glEnableVertexAttribArray(0);
    	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);

	    glUniform4f(_colorloc, 1.0f, 1.0f, 1.0f, 1.0f);		
	    glDrawArrays(GL_TRIANGLES, 0, 6);
	    
	    glUniform4f(_colorloc, 1.0f, 0.0f, 0.0f, 1.0f);		
	    glDrawArrays(GL_LINES, 6, 2); 
	    
	    glUniform4f(_colorloc, 0.0f, 0.0f, 1.0f, 1.0f);		
	    glDrawArrays(GL_POINTS, 8, 1);

	    glUniform4f(_colorloc, 1.0f, 0.0f, 0.0f, 1.0f);		
	    glDrawArrays(GL_POINTS, 9, 1);
    glUseProgram(0);

	glFlush();
}

static void 
cb_reshape(int width, int height) {
	logv("cb_reshape: width:%d, height:%d", width, height);
	glViewport (0, 0, width, height);
}

static void
cb_close() {
	logv("cb_close");
	glDeleteProgram(_program);
}

int
main(int argc, char *argv[]) {
	glutInit(&argc, argv);
	glutInitWindowSize(800, 600);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowPosition(0, 0);
	
	glutCreateWindow("AirHockey - 1");
	
	if (init() == GL_FALSE)
		return 0;

	glutDisplayFunc(cb_display);
	glutReshapeFunc(cb_reshape);
	glutCloseFunc(cb_close);

	glutMainLoop();
	return 0;
}
